#coding=cp936
import os,sys

#Auto search subdirs which only contains pics and make htmls for them
def makeit(rootdir,count=20):
    for root,dir,files in os.walk(rootdir):
        nonpiccount = 0
        pics = []
        for f in files:
            pics.append(str(root)+'\\'+f)
        for p in pics:
            if p[-3:] not in ('bmp','jpg','jpeg','png'):
                pics.remove(p)
        #xpics = (p for p in pics if p[-3:] not in ('bmp','jpg','jpeg','png'))
        #pics.sort()
        for file,text,mode in printpage(pics,str(root),count):#imgs per page, 20 for default
            f = open(file,mode)
            f.write(text)
            f.flush()
            f.close()

def printpage(datas,title,count=20):
     index = -1
     lendata = len(datas)
     remain = lendata
     curpage = title+'.html'
     nextpage,prvpage = '',''
     while 1:        
        if index >= lendata: 
            yield curpage, '\n<hr>\n<div align=left><a href="%s#%d">Previous</a>' % (prvpage,index-count-1 > 0 and index-count-1 or 0), 'a+'
            return  # generator terminated
        if index == -1: 
            yield curpage, '<h3>%s</h3><br><hr><br>\n' % (title,), 'w'
            index += 1
            continue
        if  not (index % count == 0 and index != 0):
            yield curpage, '<a name="#%d"><img src="%s"></img></a>\n' % (index,datas[index]), 'a+'
            index += 1
            continue
        else :
            nextpage = str(hash(datas[index]))+'.html'
            remain = lendata - index - 1
            yield curpage, '\n<hr>\n<div align=left><a href="%s#%d">Previous</a></div><div align=right><a href="%s">Next(%d pics remain)</a></div>' % (prvpage,index-count-1,nextpage,remain), 'a+'
            if remain == 0:return
            yield nextpage,'','w'
            prvpage = curpage
            curpage = nextpage
            index += 1
                                 
makeit(os.curdir,count=10)
print 'ok'